package com.example.jianzhioffer;

import java.util.HashSet;

/**
 * Created by Quincy on 2018/9/11.
 * 求链表交叉部分
 */
public class LinkCros {

    public class ListNode{
        int val;
        ListNode next = null;
        ListNode(int val){
            this.val = val;
        }
    }
/**
 *  先把一条链表里的数据放入set中，然后再放入第二条链表，若有相同，代表相交
 *  但是只能返回第一个相交节点
 * */
    public ListNode getCrosNode(ListNode node1, ListNode node2){
        HashSet<ListNode> set = new HashSet<>();
        ListNode crosNode = null;
        boolean res = false;
        while (node1 != null){
            set.add(node1);
            node1 = node1.next;
        }
        while (node2 != null){
            if (!set.add(node2)){
                res = true;
                crosNode = node2;
                break;
            }
            node2 = node2.next;
        }
        return crosNode;
    }

    /**
     *  寻找单链表中的中间节点
     * */
    public ListNode findMidNode(ListNode node){
        //奇数时中间节点，偶数时后面一个
        ListNode fast = node;
        ListNode slow = node;
        while (fast != null && fast.next != null ){
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow;
    }
}
